// ignore_for_file: library_private_types_in_public_api

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';


typedef TreeSelectSingleDataFun = Function(Map map, String id, String value);

class TreeSelectSingleView extends StatefulWidget {
  // 子集Key
  final String childrenKey;
  // idKey
  final String idKey;
  // valueKey
  final String valueKey;
  // 数据
  final List dataList;
  // 是否默认展开;
  final bool expand;
  // 是否可以选择上层
  final bool selectParent;
  // 取消回调
  final Function? onCancel;
  // 回调
  final TreeSelectSingleDataFun? onConfirm;

  const TreeSelectSingleView({
    required this.childrenKey,
    required this.idKey,
    required this.valueKey,
    required this.dataList,
    this.expand = true,
    this.selectParent = false,
    this.onCancel,
    this.onConfirm,
    Key? key,
  }) : super(key: key);

  @override
  _TreeSelectSingleViewState createState() => _TreeSelectSingleViewState();
}

class _TreeSelectSingleViewState extends State<TreeSelectSingleView> {
  TextEditingController controller = TextEditingController();

  List dataList = [];

  @override
  void initState() {
    super.initState();
    dataList.addAll(jsonDecode(jsonEncode(widget.dataList)));
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  bool searchMake(List dataList, String value) {
    bool parentShow = false;
    for (Map item in dataList) {
      if (item[widget.childrenKey] != null &&
          item[widget.childrenKey].length != 0) {
        item['show'] = searchMake(item[widget.childrenKey] ?? [], value);
        parentShow = parentShow || item['show'];
      } else {
        if (item[widget.valueKey].contains(value)) {
          item['show'] = true;
          parentShow = true;
        } else {
          item['show'] = false;
        }
      }
    }
    return parentShow;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(child: Container()),
        Container(
          padding: EdgeInsets.all(10.w),
          decoration: BoxDecoration(
            color: Colors.white,
            // 圆角设置
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(18.w),
              topRight: Radius.circular(18.w),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              InkWell(
                onTap: () {
                  Navigator.pop(context);
                  if (widget.onCancel != null) {
                    widget.onCancel!();
                  }
                },
                child: Container(
                  padding: EdgeInsets.only(left: 10.w),
                  color: Colors.white,
                  child: Text(
                    '取消',
                    style:
                        TextStyle(color: Colors.grey.shade500, fontSize: 14.w),
                  ),
                ),
              ),
              Text(
                '请选择',
                style: TextStyle(color: Colors.black, fontSize: 16.w),
              ),
              Container(
                padding: EdgeInsets.only(right: 10.w),
                color: Colors.white,
                child: Text(
                  '',
                  style: TextStyle(color: Colors.blue, fontSize: 14.w),
                ),
              ),
            ],
          ),
        ),
        Container(
          color: Colors.white,
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
            decoration: BoxDecoration(
              color: const Color(0xffF5F6F7),
              borderRadius: BorderRadius.circular(100.w),
            ),
            child: TextField(
              maxLines: 1,
              controller: controller,
              textAlignVertical: TextAlignVertical.center,
              decoration: InputDecoration(
                isDense: true,
                fillColor: const Color(0xffF5F6F7),
                border: InputBorder.none,
                constraints: BoxConstraints(maxHeight: 36.w),
                contentPadding:
                    EdgeInsets.only(left: 0, top: 0, bottom: 0, right: 15.w),
                prefixIcon:
                    const Icon(Icons.search_rounded, color: Color(0x991d2541)),
                hintText: "请输入搜索内容",
                hintStyle: TextStyle(
                  color: const Color(0x991d2541),
                  fontSize: 14.sp,
                ),
              ),
              cursorColor: const Color(0xff1D2541),
              style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xff1D2541),
              ),
              onChanged: (value) {
                Future.delayed(const Duration(milliseconds: 500), () {
                  searchMake(dataList, value);
                  setState(() {});
                });
              },
            ),
          ),
        ),
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(top: 10.w, left: 5.w),
          height: 520.w,
          child: MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: ListView(
                shrinkWrap: true,
                children: List.generate(
                    dataList.length,
                    (index) => TreeSelectSingleItemView(
                          childrenKey: widget.childrenKey,
                          idKey: widget.idKey,
                          valueKey: widget.valueKey,
                          level: 0,
                          itemData: dataList[index],
                          expand: widget.expand,
                          selectParent: widget.selectParent,
                          onConfirm: widget.onConfirm,
                        ))),
          ),
        ),
      ],
    );
  }
}

class TreeSelectSingleItemView extends StatefulWidget {
  // 子集Key
  final String childrenKey;
  // idKey
  final String idKey;
  // valueKey
  final String valueKey;
  // 层级
  final int level;
  // 当前层数据
  final Map itemData;
  // 是否可以选择上层
  final bool selectParent;
  // 是否默认展开;
  final bool expand;
  // 回调
  final TreeSelectSingleDataFun? onConfirm;

  const TreeSelectSingleItemView({
    required this.childrenKey,
    required this.idKey,
    required this.valueKey,
    required this.level,
    required this.itemData,
    required this.selectParent,
    required this.expand,
    required this.onConfirm,
    Key? key,
  }) : super(key: key);

  @override
  _TreeSelectSingleItemViewState createState() =>
      _TreeSelectSingleItemViewState();
}

class _TreeSelectSingleItemViewState extends State<TreeSelectSingleItemView> {
  @override
  void initState() {
    super.initState();
    if (widget.itemData['expand'] == null) {
      if (widget.itemData[widget.childrenKey] != null &&
          widget.itemData[widget.childrenKey].length != 0) {
        widget.itemData['expand'] = widget.expand;
      } else {
        widget.itemData['expand'] = widget.expand;
      }
    }
    if (widget.itemData['show'] == null) {
      widget.itemData['show'] = true;
    }
    setState(() {});
  }

  itemClick(Map itemData) {
    if (widget.selectParent) {
      Navigator.pop(context);
      if (widget.onConfirm != null) {
        widget.onConfirm!(
            itemData, itemData[widget.idKey], itemData[widget.valueKey]);
      }
    } else {
      if ((itemData[widget.childrenKey] == null ||
              itemData[widget.childrenKey].isEmpty) &&
          widget.onConfirm != null) {
        widget.onConfirm!(
            itemData, itemData[widget.idKey], itemData[widget.valueKey]);
        Navigator.pop(context);
      } else {
        iconClick(itemData);
      }
    }
  }

  iconClick(Map itemData) {
    setState(() {
      itemData['expand'] = !itemData['expand'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return widget.itemData['show']
        ? Container(
            padding: EdgeInsets.only(top: 8.w),
            child: Column(
              children: [
                InkWell(
                  onTap: () => itemClick(widget.itemData),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      InkWell(
                        onTap: () => iconClick(widget.itemData),
                        child: Row(
                          children: [
                            Container(
                              padding: EdgeInsets.only(
                                left: widget.level * 26.w,
                              ),
                              child: (widget.itemData[widget.childrenKey] !=
                                          null &&
                                      widget.itemData[widget.childrenKey]
                                          .isNotEmpty)
                                  ? Icon(
                                      widget.itemData['expand']
                                          ? Icons.keyboard_arrow_down
                                          : Icons.keyboard_arrow_right,
                                      color: const Color(0x991d2541),
                                      size: 22.w,
                                    )
                                  : SizedBox(
                                      width: 22.w,
                                    ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        '${widget.itemData[widget.valueKey] ?? ''}',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.black, fontSize: 14.w),
                      ),
                      Expanded(child: Container()),
                      (widget.selectParent ||
                              !(widget.itemData[widget.childrenKey] != null &&
                                  widget
                                      .itemData[widget.childrenKey].isNotEmpty))
                          ? Icon(Icons.keyboard_arrow_right,
                              color: Colors.grey.shade500)
                          : Container(),
                    ],
                  ),
                ),
                widget.itemData['expand']
                    ? Column(
                        children: List.generate(
                            (widget.itemData[widget.childrenKey] ?? []).length,
                            (index) => TreeSelectSingleItemView(
                                  childrenKey: widget.childrenKey,
                                  idKey: widget.idKey,
                                  valueKey: widget.valueKey,
                                  level: widget.level + 1,
                                  itemData: widget.itemData[widget.childrenKey]
                                      [index],
                                  onConfirm: widget.onConfirm,
                                  selectParent: widget.selectParent,
                                  expand: widget.expand,
                                )))
                    : Container(),
              ],
            ),
          )
        : Container();
  }
}
